class: title-slide, bottom, right background-image: url(https://images.unsplash.com/photo-1459908676235-d5f02a50184b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1170&q=80) background-size: cover ### Plotting # ### **Miriam Lerma**<br> June 2023 --- name: index class: title-slide, inverse # Index - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [maps](#custom-map) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [export](#export) - [contact](#out) --- class: title-slide, inverse # Today .pull-left[ **Your profile** - You know how to use a Rmd document - You know how to install packages **Goals of today** - Create plots and maps in R - Change the apparence of the plots - Export you plots **Pauses and questions** - Exercises and 10 minute pauses for catching up - You can stop me to ask questions or use [this link
]( https://docs.google.com/document/d/1uG7a2_hkdaKQm5gKXRBFf6gcyoUBan2e69gL3ZKcwg8/edit?usp=sharing) ] .pull-right[ We will use the packages ```r devtools::install_github("MiriamLL/sula") devtools::install_github("MiriamLL/GermanNorthSea") devtools::install_github("MiriamLL/seamonas") install.packages('sf') install.packages('ggspatial') install.packages('plotly') ``` ] --- class: inverse # References .pull-left[ Tutorials/Books - [gg is for Grammar of Graphics](https://pkg.garrickadenbuie.com/trug-ggplot2)<br> - [Introduccion to ggplot](https://englelab.gatech.edu/useRguide/introduction-to-ggplot2.html) - [r4ds](https://r4ds.had.co.nz/data-visualisation.html) - [Geocomputation with R](https://r.geocompx.org/attr.html) - [R Graphics Cookbook](https://r-graphics.org/) - [Allison Horst tutorial](https://allisonhorst.github.io/rice-data-viz/) Gallery/Portafolios - [Data-Viz-Bookmarks](https://spcanelon.notion.site/spcanelon/Data-Viz-Bookmarks-dc01718020bd4fd6a8a4ca80e6bce933)<br> - [RGraphGallery](https://www.r-graph-gallery.com/) <br> - [DataToViz](https://www.data-to-viz.com/) <br> - [Coolors](https://coolors.co/) <br> ] .pull-right[ <img src="https://cdn.myportfolio.com/45214904-6a61-4e23-98d6-b140f8654a40/9a306c0a-dac8-413d-ba2e-cc7fd4c4d5c8_rw_1920.png?h=c802991088a9623f1f7aa18c470797ee" height="300" /> ] --- name: theory ## 1.1. Theory The objective of a graph/plot/map/chart is to communicate. <br> In science, the idea is to show information in a clear and understandable way. <img src="http://www.typesofgraphs.com/wp-content/uploads/2015/12/Typesofgraphs.png" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Plotting is transforming data to visualizations that vary in shape, size and colors. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_1.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory There are many ways to plot data, and different ways to interpretate the graphs. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_2.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Which one is more intuitive? <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_4.jpg" height="350" /> Fuente: [VizThinker](https://paldhous.github.io/ucb/2016/dataviz/week2.html) --- ## 1.1. Theory Which one should I use? You can try different plots and choose the one that betters tells the story. **Tableau Public** has a suggestion on which graph to use according to the type of data you are using. <img src="https://paldhous.github.io/ucb/2016/dataviz/img/class2_5.jpg" height="300" /> --- name: intro ## 1.2. Intro There are many packages to create plots in R. - Here we will use **ggplot2**. ggplot is the most versatile one, and from which you can find more help and inspiration. --- ## 1.2. Intro A graph can be divided in three main components: - **Data** (data): which are the variables that we plot. - **Geometry** (geom): a geometric object such as dots, lines, bars. - **Aesthetics** (aes): the aesthetic attributes to a geometric object, such as position, color, shape and size. Each component is displayed as **layers** like in GIS (Geographic information systems). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/300Geoms.png?raw=true" height="200" /> Source: [ggplot2 book](https://englelab.gatech.edu/useRguide/working-with-data-overview.html) --- ## 1.3. Data The package ggplot is already included in tidyverse. <br> If you have installed tidyverse you just need to call your package. ```r library(tidyverse) ``` If not you can also install it separately. ```r install.packages("ggplot2") ``` --- ## 1.3. Data For the exercises, we can use data from packages.<br> Lets add our object to our **environment**. Package with data ```r library(palmerpenguins) penguins<-penguins ``` Call library **ggplot2**. ```r library(ggplot2) ``` --- ## 1.3. Data First step: add data to a plot. ```r ggplot(data=penguins) ``` <!-- --> We told ggplot what data frame we want to use, but need to give instruction on how to plot. <br> --- ## 1.3. Add axis Using **mapping** we tell ggplot what to plot in the x and y axis.<br> **Note** that the axis are columns from your data frame. This is when having tidydata is important. ```r ggplot(data=penguins, * mapping=aes(x=bill_length_mm, * y=bill_depth_mm)) ``` <!-- --> --- ## 1.3. Geometry The next step is to give it a geometry, in this case we say plot points with the argument **geom_point** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_point() ``` <!-- --> It would likely show a **warning**. <br> This is because NAs are not going to be plotted and R is trying to warn you. --- ## 1.3. Geometry There are many **geometries**. Most of them start with **geom_*** <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/302geometries.png?raw=true" height="400" /> --- ## 1.3. Geometry Examples of most common geometries are to be found on [R-graph-gallery](https://r-graph-gallery.com/) .pull-left[ <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/302examples.png?raw=true" height="150" /> <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/306examples.png?raw=true" height="200" /> ] .pull-right[ <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/307examples.png?raw=true" height="200" /> ] --- ## 1.4. Common mistakes The most common mistakes with plotting are the same as while writing code. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/023DebuggingBingo.jpg?raw=true" height="450" /> --- ## 1.4. Common mistakes Not having **tidydata** is also a very common problem. So remember: <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/104TidyData.jpg?raw=true" height="400" /> [Allison Horst](https://allisonhorst.com/) --- ## 1.4. Common mistakes Other common mistakes specific to ggplot are: - Forgetting a plus symbol ( **+** ) ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm)) geom_point() ``` - Adding the **+** on the wrong order ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm)) +geom_point() ``` - Forgetting a parenthesis ```r ggplot(penguins, * aes(x=bill_length_mm,y=flipper_length_mm)+ geom_point() ``` ## 1.5. Simplify We can skip writing **data=** and **mapping=** by just following the order of the elements. Both codes give the same output. .pull-left[ Including the elements. ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm, y=flipper_length_mm))+ geom_point() ``` <!-- --> ] .pull-right[ Simplified example. ```r ggplot(penguins, aes(x=bill_length_mm, y=flipper_length_mm,))+ geom_point() ``` <!-- --> ] --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Run lines 31 to 53. ```r ggplot(data=penguins,mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ geom_point() ``` ] .pull-right[ Until here: - [index](#index) - [theory](#theory) Next part: - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [maps](#custom-map) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [export](#export) - [contact](#out) ] --- name: geometries class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1570386230314-9fe8204c6f80?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1108&q=80) background-size:cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Geometries</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Try some different</span> ] # 2. Geometries --- name: scatterplot ## 2.1. Scatterplots The scatterplot is most useful for displaying the relationship between two continuous variables. Each dot represents an observation. Their position on the x (horizontal) and y (vertical) axis represents the values of the 2 variables. The argument to create scatterplots is **geom_point** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_point() ``` <!-- --> See more [scatterplots](https://r-graph-gallery.com/scatterplot.html) --- name: lines ## 2.2. Line chart A line chart or line graph displays the evolution of one or several numeric variables. <br> Data points are connected by straight line segments. The argument to create line charts is **geom_line()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_line() ``` <!-- --> See more [line chart](https://r-graph-gallery.com/line-plot.html) --- name: barplot ## 2.3. Barplot A barplot is used to display the relationship between a numeric and a categorical variable.<br> The argument to create barplots is **geom_bar()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_bar() ``` Error: stat_count() can only have an x or y aesthetic. Different from the logic of the previous plots, we need to tell what do you want inside the bars by adding **stats=**. --- ## 2.3. Barplot The argument **stats=** is to be included inside the parethesis of **geom_bar** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_bar(stat='identity') ``` <!-- --> See more [barplots](https://r-graph-gallery.com/barplot.html) --- name: boxplot ## 2.4. Boxplot Boxplot is probably the most commonly used chart type to compare distribution of several groups.<br> It visualises five summary statistics (the median, two perfcentiles and two whiskers). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/305boxplot.png?raw=true" height="350" /> Source: [Boxplot explanation](https://www.leansigmacorporation.com/box-plot-with-minitab/) --- ## 2.4. Boxplot The boxplot compactly displays the distribution of a continuous variable. The argument to create boxplots is **geom_boxplot()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm))+ * geom_boxplot() ``` <!-- --> --- ## 2.4. Boxplot Often we will like to use boxplots to visualize differences between groups. Using the argument **group=* inside mapping to create boxplots per group. ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=bill_depth_mm, * group=species))+ geom_boxplot() ``` <!-- --> See more [boxplots](https://r-graph-gallery.com/boxplot.html) --- name: trajectory ## 2.5. Trajectory For plotting moving objects (such as planes or birds), connecting points with a line is the most common visualization used. -- For today exercises, install **sula**. ```r devtools::install_github("MiriamLL/sula") ``` The package **sula** contains tracking data from Masked boobies on Easter Island. ```r library(sula) ``` To plot a trajectory, lets load data from the package **sula**. Then, get data in the environment. ```r tracking_data<-sula::GPS_raw ``` The data frame contains the columns **Latitude** and **Longitude**. --- ## 2.5. Trajectory The argument to create trajectories is **geom_path()**. By definition geom_path() connects the observations in the order in which they appear in the data. ```r ggplot(data=tracking_data, mapping=aes(x=Latitude, y=Longitude)) + * geom_path() ``` <!-- --> --- name: maps ## 2.6. Maps R is an great tool for geospatial data analysis. The book [geocomputation with R](https://r.geocompx.org/attr.html) is a recommended guide to create maps in R (and is constantly updated). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/306Book.png?raw=true" height="400" /> --- ## 2.6. Maps For today exercises, install **GermanNorthSea**. ```r devtools::install_github("MiriamLL/GermanNorthSea") ``` The package **GermanNorthSea** compiles shapefiles from the North Sea. ```r library(GermanNorthSea) ``` To see the containing shapefiles go to my [github](https://github.com/MiriamLL/GermanNorthSea). To add shapefile to environment. ```r Europe<-German_land ``` **Note** that shapefiles can be an **sf** object. An sf object is different from a data frame, if we click on the object is not clear what it contains. ```r class(Europe) ``` ``` ## [1] "sf" "data.frame" ``` --- ## 2.6. Maps The argument to plot **sf** (simple features) objects is **geom_sf()** By definition geom_sf() uses a unique aesthetic: geometry, giving an column of class sfc containing simple features data. ```r ggplot(data=Europe)+ * geom_sf() ``` <!-- --> --- class: inverse # Pause .pull-left[ Practice
<br> Open the file [03ExercisesPlotting.Rmd](https://github.com/MiriamLL/R_intro/blob/master/03ExercisesPlotting.Rmd) Run lines 63 to 107. ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) Next part: - [maps](#custom-map) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [export](#export) - [contact](#out) ] --- name: custom-maps class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1554033551-050e208bcaf2?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=800) background-size: cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Maps</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Level up</span> ] --- ## 3.Maps Some elements from a map - Shapefile - Coords - Scale - Arrow --- ## 3.1. Load shapefile Download the shapefile from [Europe](https://github.com/MiriamLL/R_intro/blob/master/Downloads/Europe.shp) Give the directory. Either by calling the package **here**. ```r library(here) ``` Or manually add the directory where your shapefile is. ```r My_directory<-here('Downloads') list.files(My_directory) ``` ``` ## [1] "Europe.dbf" "Europe.prj" "Europe.sbn" "Europe.sbx" ## [5] "Europe.shp" "Europe.shx" "My_plot.png" "penguins1.csv" ## [9] "penguins2.csv" "penguins3.txt" "penguins4.xlsx" ``` ```r My_shapefile<-paste0(My_directory,"/Europe.shp") ``` --- ## 3.1. Load shapefile Call the package sf to read the shapefiles into R. ```r library(sf) ``` Use the argument **st_read** to load your shapefile. ```r Europe_shp<-st_read(My_shapefile) ``` ``` ## Reading layer `Europe' from data source ## `C:\Users\lerma\OneDrive\Documents\2MonTrack\2023\Teaching\R_intro\R_intro\Downloads\Europe.shp' ## using driver `ESRI Shapefile' ## Simple feature collection with 54 features and 2 fields ## Geometry type: MULTIPOLYGON ## Dimension: XY ## Bounding box: xmin: -31.26575 ymin: 32.39748 xmax: 69.07032 ymax: 81.85737 ## Geodetic CRS: WGS 84 ``` Note that it gives us the Geodetic CRS: WGS 84 --- ## 3.2. Create a basic map Load the package ggplot2 ```r library(ggplot2) ``` Plot your shapefile using **geom_sf** ```r ggplot(data = Europe_shp)+ geom_sf() ``` <!-- --> --- ## 3.3. Add limits Reduce to focus in your area of interest ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56)) ``` <!-- --> --- ## 3.3. Add limits ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) ``` <!-- --> --- name: scale ## 3.4. Add scale Load the package ggspatial to add a scale and an north arrow ```r library(ggspatial) ``` br is from bottom right ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W"))+ scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N"))+ annotation_scale(location = "br") ``` <!-- --> --- name: arrow ## 3.5. Add arrow tl is for top left which_north preferably true (see why here) north_arrow_fancy_orienteering (see other styles here) ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W"))+ scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N"))+ annotation_scale(location = "br")+ annotation_north_arrow(location = "tl") ``` <!-- --> --- ## 3.6. Add points The package **seamonas** contains data from a hypothetical survey. ```r library(seamonas) ``` Add the data to your environment. <br> The data frame contains the columns **latitude** and **longitude**. ```r survey_4326<-survey_4326 ``` Plot the data from the survey. ```r ggplot()+ geom_point(data=survey_4326, aes(x = longitude, y= latitude)) ``` <!-- --> --- ## 3.7. Add points Now add the points into the your map. ```r ggplot(data = Europe_shp)+ geom_sf()+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W"))+ scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N"))+ annotation_scale(location = "br")+ annotation_north_arrow(location = "tl") + geom_point(data=survey_4326,aes(x = longitude,y= latitude)) ``` <!-- --> --- ## 3.8. CRS A coordinate reference system (CRS) refers to the way in which spatial data that represent the earth’s surface. .pull-left[ CRS: 4326 <!-- --> ] .pull-right[ CRS: 3035 <!-- --> ] --- ## 3.8. CRS It is important to understand the coordinate system that your data uses - particularly if you are working with different data stored in different coordinate systems. In our particular case, not using the correct projection might derive in calculation mistakes and differences between studies. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/313CRSdeformation.jpg?raw=true" height="200" /> --- ## 3.8. CRS To transform our shapefile to other coordinate system **st_transform** from the package **sf** can be used. ```r Europe_3035<-sf::st_transform(Europe_shp, 3035) ``` Now the xlim and ylim can be in degrees. ```r ggplot(data=Europe_3035)+ geom_sf() ``` <!-- --> --- ### 3.8. CRS To **zoom-in**, the argument **coord_sf()** can be used. **For this map, I am using the CRS 3035**. Thus, my **xlim** and my **ylim** are in those units. ```r ggplot(data=Europe_3035)+ geom_sf()+ * coord_sf(xlim = c(3790000,4250000), ylim = c(3350000,3680000)) ``` <!-- --> --- name: aesthetics class: title-slide, inverse, bottom background-image: url(https://images.unsplash.com/photo-1460661419201-fd4cecdf8a8b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=580&q=80) background-size:cover .pull-right[ # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Aesthetics</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Bring some colors</span> ] --- # 4.1. Aesthetics **Aesthetics** are for controlling the overall appearance of graphs. You can change almost every tiny detail to create the plot that you want. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/308parts-ggplot.png?raw=true" height="350" /> Source [ggplot2 elements](https://isabella-b.com/blog/ggplot2-theme-elements-reference/)<br> Download [pdf](https://isabella-b.com/files/ggplot2-theme-elements-reference-v2.pdf) --- # 4.1. Aesthetics There are many elements, but I will not go into detail to most of them. For going into more detail the book [R Graphics cookbook](https://r-graphics.org/) is a great guide. <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/310Cookbook.jpg?raw=true" height="300" /> --- name: theme ## 4.2. Theme Themes are a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. Themes can be used to give plots a consistent customized look. .pull-left[ The theme can be changed using **theme_classic()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ geom_point()+ * theme_classic() ``` <!-- --> ] .pull-right[ The theme can be changed using **theme_bw()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ geom_point()+ * theme_bw() ``` <!-- --> ] --- ## 4.3. Theme There are many different themes. It would depend on the type of graph and taste to choose. .pull-left[ he theme can be changed using **theme_minimal()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ geom_point()+ * theme_minimal() ``` <!-- --> ] .pull-right[ he theme can be changed using **theme_void()** ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ geom_point()+ * theme_void() ``` <!-- --> ] --- name: color ## 4.4. Color To go beyond the default colors, the package ggplot2 allows you to change colors on the elements of your plot. To select the colors there are several ways, I use by **name** or **hex codes**. Using by **name**, the default names are used. .pull-left[ You can see a complete list of the 657 colors typing colors(). ```r colors() ``` ] .pull-right[ You can also see the color and the name by opening this [link](https://github.com/MiriamLL/R_intro/blob/master/Images/311colornamesplot.png?raw=true). <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/311colornamesplot.png?raw=true" height="300" /> ] --- ## 4.5. Color To use the color by **name** in your plot you can add it, for example, inside the brackets of geom_point() ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ * geom_point(color='red') ``` <!-- --> --- ## 4.6. Color Colors can also be defined by their **hex code**. An hex code is the code of the color in 6 digits. To find the hex code there are tons of webpages. I personally like [coolors](https://coolors.co/palettes/trending). In [coolors](https://coolors.co/palettes/trending) go to explore>put your cursor on top of the color you like>click>paste on your code <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/312coolors.png?raw=true" height="300" /> --- ## 4.6. Color To use the color by **hex code** in your plot you can add it, for example, inside the brackets of geom_point(). **Note** that different from using colors by name, here you need to add a **#**. ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm))+ * geom_point(color='#c1121f') ``` <!-- --> --- ## 4.6. Color If you wish to colour point on a scatterplot by a third categorical variable, then add **colour =** within your aes brackets. This tells ggplot that this third variable will colour the points. ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm, * color=species))+ geom_point() ``` <!-- --> --- ## 4.6. Color The colors, when not declared, are selected by default.<br> To customize your colors you can add more arguments. <br> The argument **scale_colour_manual** allows you to customize those colors. <br> You can add colors by **name**.<br> ```r ggplot(data=penguins, mapping=aes(x=bill_length_mm,y=flipper_length_mm, color=species))+ geom_point()+ * scale_colour_manual(values = c("purple", "yellow", "orange")) ``` <!-- --> --- ## 4.6. Color For a map, we can change the color of our shapefile by adding the argument **colour** and **fill** inside the brackets of **geom_sf()** ```r ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen") ``` <!-- --> --- name: background ## 4.7. Background colors To change the background, we can add the arguments inside the argument **theme**. I added here the **coord_sf** to focus in a specific area. ```r ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen")+ * theme(panel.background = element_rect(fill = 'lightskyblue2'))+ coord_sf(xlim = c(3,9), ylim = c(53,56)) ``` <!-- --> --- ## 4.7. Background colors To remove the grids from the background, we can add **element_blank** inside the argument **theme**. ```r ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen")+ theme( * panel.grid.major = element_blank(), * panel.grid.minor = element_blank(), panel.background = element_rect(fill = 'lightskyblue2'))+ coord_sf(xlim = c(3,9), ylim = c(53,56)) ``` <!-- --> --- name: axis ## 4.8. Axis legends To change the legends on the axis, we can add the arguments **xlab** and **ylab** ```r ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen")+ theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = 'lightskyblue2'))+ coord_sf(xlim = c(3,9), ylim = c(53,56))+ * xlab('Longitude')+ylab('Latitude') ``` <!-- --> --- ## 4.8. Axis legends To change the axis labels, it is usually more simple with other plots, but with maps we need to specify with the argument **scale_x_continuous** and **scale_y_continuous**. ```r ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen")+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = 'lightskyblue2'))+ coord_sf(xlim = c(3,9), ylim = c(53,56))+ * scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + * scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) ``` <!-- --> --- ## 3.3. Add colors I copy the hex colors from coolors ```r Europe_plot<-ggplot(data = Europe_shp)+ geom_sf(colour = "#edf2f4", fill = "#2b2d42", size=0.5) Europe_plot ``` <!-- --> Change background color ```r Europe_plot<-Europe_plot+ theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = '#edf2f4'), legend.background = element_rect(fill = '#edf2f4')) Europe_plot ``` <!-- --> --- ## 4.9. Object To also simplify the process, you can save your plot as an object in the environment. ```r My_plot<-ggplot(data = Europe)+ geom_sf(color = "olivedrab4", fill = "darkseagreen") ``` And add all the elements to your object using the **+** ```r *My_plot+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = 'lightskyblue2'))+ coord_sf(xlim = c(3,9), ylim = c(53,56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) ``` <!-- --> --- ## 4.10. Cheat sheet Help>CheatSheets>Data Visualization with ggplot <img src="https://github.com/MiriamLL/R_intro/blob/master/Images/314cheatsheet.png?raw=true" height="400" /> --- class: inverse # Pause .pull-left[ Practice
<br> Change the theme, color, or other elements of the following map. ```r ggplot(data = Europe)+ geom_sf(color = _______, fill = _______)+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = _______))+ coord_sf(xlim = c(3,9), ylim = c(53,56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) ``` ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) Next part: - [export](#export) - [contact](#out) ] --- ## 5.1. Interactive Graphs can be interactive. To install package **plotly**. ```r install.packages('plotly') ``` Call the package. ```r library(plotly) ``` See more about [plotly](https://plotly.com/r/) There are many other useful packages such as: - [tmap](https://cran.r-project.org/web/packages/tmap/vignettes/tmap-getstarted.html) --- ## 5.1. Interactive The function **ggplotly** converts a ggplot() object to a plotly object. ```r *ggplotly(Europe_plot+ geom_point(data=survey_4326, aes(x = longitude, y= latitude), color='#2a9d8f', size=0.1) ) ```
--- ## 5.2. Interactive Control the information displayed by adding more elements in geom_point ```r ggplotly(Europe_plot+ geom_point(data=survey_4326, aes(x = longitude, y= latitude, * color=date)) ) ```
--- # 5.3. Animate We can also create animated plots. <img src="https://github.com/MiriamLL/miriamlerma_/blob/main/animation.gif?raw=true" height="350" /> However, doing this during a R session would be very time consuming. To recreate the animation, you can see my [blog](www.miriam-lerma.com/blog) --- class: inverse # Pause .pull-left[ Practice
<br> Load your shapefile. ```r My_directory<-here('Downloads') My_shapefile<-paste0(Directory,"/Europe.shp") Europe_shp<-st_read(My_shapefile) ``` Load data frame. ```r survey_4326<-seamonas::survey_4326 ``` Change elements of the map. ```r ggplot(data = Europe_shp)+ geom_sf(colour = "#edf2f4", fill = "#2b2d42", size=0.5) + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_rect(fill = '#edf2f4'), legend.background = element_rect(fill = '#edf2f4'))+ coord_sf(xlim = c(6, 10),ylim = c(53, 56))+ scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) + scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N"))+ geom_point(data=survey_4326, aes(x = longitude, y= latitude), color='#2a9d8f', size=0.1) ``` ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [maps](#custom-map) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) Next part: - [export](#export) - [contact](#out) ] --- name: export background-image: url(https://images.unsplash.com/photo-1465161191540-aac346fcbaff?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=870&q=80) background-size: cover # <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Maps</span> ### <span style=" font-weight: bold; color: #e5e5e5 !important;border-radius: 4px; padding-right: 4px; padding-left: 4px; background-color: #003049 !important;" >Level up</span> --- # 6. Export --- ## 6.1. ggsave To export a plot there is **ggsave** You need to specify the folder where you want the plot to be exported to. ```r ResultsFolder<-here('Downloads') ``` Using the function **ggsave** it would be exported. You can change the extention (.png,.jpg,etc), the width, lenght, units and dpi. ```r ggsave(My_plot, filename = paste0(ResultsFolder,"/My_plot.png"), width = 24, height = 24, units = "in", dpi = 500) ``` --- ## 6.2. word Another way to export maps is to use a Rmd file like the one on the [link](https://raw.githubusercontent.com/MiriamLL/R_intro/master/04PlotWord.Rmd). For exporting to word, consider: Not including the code, write **echo=FALSE** in your code chunk. Not including messages, write **message=FALSE** in your code chunk. Not including warnings, write **warning=FALSE** in your code chunk. ```r {r,echo=FALSE, echo=FALSE, warning=FALSE, message=FALSE} ``` To adjust the size of the maps you can specify the fig.height and fig.width in the code chunk ```r {r,echo=FALSE, echo=FALSE, warning=FALSE, message=FALSE,fig.height=10, fig.width=10} ``` --- ## 6.3. html The best way to export interactive maps is to use Rmd to html like the one on the [link](https://raw.githubusercontent.com/MiriamLL/R_intro/master/05PlotInteractive.Rmd). Just remember to change the output on the YAML. ```r output: html_document ``` --- class: inverse # Pause .pull-left[ Practice
<br> Change some elements from the Rmds to export your data. ] .pull-right[ Until here: - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [export](#export) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [contact](#out) ] --- name: out class: title-slide background-image: url(https://images.unsplash.com/photo-1514679347725-10436adc23a8?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=862&q=80) background-size: cover ### Back to - [index](#index) - [theory](#theory) - [scatterplot](#scatterplot) - [line chart](#lines) - [barplot](#barplot) - [trajectory](#trajectory) - [maps](#maps) - [shapefiles](#shapefiles) - [limits](#limits) - [scale](#scale) - [arrow](#arrow) - [aesthetics](#aesthetics) - [theme](#theme) - [color](#color) - [background](#background) - [axis](#axis) - [export](#export) .right[ ### Contact This materials are free of use <br> Download the presentation here: [
github](https://github.com/MiriamLL/R_intro) and [
webpage](https://www.miriam-lerma.com/posts/2023-06-06-plotting/) ] .right[ [
Home](https://www.miriam-lerma.com/teaching.html) [
Index ](https://miriamll.github.io/R_intro/Plotting_0606.html#2) ] <br>